#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
#include <pthread.h>
using namespace std;
int ticket = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *getTicket(void *arg)
{
    string name = static_cast<const char *>(arg);
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (ticket > 0)
        {
            usleep(1000);
            cout << name << "正在抢票:" << ticket << endl;
            --ticket;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        usleep(1000);
    }

    return nullptr;
}

int main()
{
    pthread_t t1, t2, t3, t4, t5;
    pthread_create(&t1, nullptr, getTicket, (void *)"thread 1");
    pthread_create(&t2, nullptr, getTicket, (void *)"thread 2");
    pthread_create(&t3, nullptr, getTicket, (void *)"thread 3");
    pthread_create(&t4, nullptr, getTicket, (void *)"thread 4");
    pthread_create(&t5, nullptr, getTicket, (void *)"thread 5");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);
    pthread_join(t5, nullptr);
    return 0;
}